package com.ygqh.baby.controller.os;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Logistics;
import com.ygqh.baby.controller.mobile.BaseController;
import com.ygqh.baby.model.kdniao.response.Data;
import com.ygqh.baby.model.kdniao.response.LogisticsTrackingResponse;
import com.ygqh.baby.model.kdniao.response.Traces;
import com.ygqh.baby.po.LogisticsTraces;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.LogisticsTracesService;
import com.ygqh.baby.service.WxMpMessageService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.KdNiaoUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/os/kdniao")
public class KdNiaoCallBack extends BaseController {
	private final static ExecutorService traceCallBack = Executors.newFixedThreadPool(3);
	private final static ExecutorService appendTracesDataBase = Executors.newFixedThreadPool(3);
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WxMpMessageService wxMpMessageService;
	@Autowired
	private LogisticsTracesService logisticsTracesService;

	@RequestMapping("KdNiaoTraceCallBack")
	public void KdNiaoTraceCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String, String> map = getParameterMap(parameterMap);
		String RequestData = map.get("RequestData");
		traceCallBack.execute(() -> {
			if (StringUtil.isNotBlank(RequestData)) {
				System.err.println(RequestData);
				LogisticsTrackingResponse res = JSON.parseObject(RequestData, LogisticsTrackingResponse.class);
				doKdNiaoTraceCallBack(res);

			}
		});

		KdNiaoUtil.returnMessageToKuaiDiNiao(response);

	}

	public void test(HttpServletRequest request, HttpServletResponse response) throws Exception {

		LogisticsTrackingResponse res = new LogisticsTrackingResponse();

		res.seteBusinessId("1261725");
		res.setCount("1");
		res.setPushTime(DateConvertUtils.parse("2018-05-20 19:28:30", DateConvertUtils.DATE_TIME_FORMAT));
		List<Data> dataList = new ArrayList<>();
		Data data = new Data();
		data.seteBusinessId(res.geteBusinessId());
		data.setShipperCode("ZTO");
		data.setState("2");
		data.setSuccess(true);
		data.setOrderCode("180520872086");
		data.setCallBack("180520872086_18666");
		data.setLogisticCode("632957419798");
		dataList.add(data);
		List<Traces> tracesList = new ArrayList<>();

		Traces traces1 = new Traces("[北京市]北京平谷的壹果[13552989818]已揽收", res.getPushTime(), "");
		Traces traces2 = new Traces("[北京市]快件离开北京平谷已发往北京", res.getPushTime(), "");
		Traces traces3 = new Traces("[北京市]快件离开北京已发往清华大学", res.getPushTime(), "");
		Traces traces4 = new Traces("[北京市]快件已到达清华大学", res.getPushTime(), "");
		Traces traces5 = new Traces("[北京市]清华大学的高岳飞18911997511[18911997511]正在派件", res.getPushTime(), "");
		Traces traces6 = new Traces("[北京市]快件已在清华大学签收 签收人：本人,感谢您使用中通快递，期待再次为您服务!", res.getPushTime(), "");

		tracesList.add(traces1);
		tracesList.add(traces2);
		tracesList.add(traces3);
		tracesList.add(traces4);
		tracesList.add(traces5);
		tracesList.add(traces6);
		data.setTraces(tracesList);

		res.setData(dataList);
		doKdNiaoTraceCallBack(res);

	}

	private void doKdNiaoTraceCallBack(LogisticsTrackingResponse res) {
		List<Data> dataList = res.getData();
		appendTracesDataBase(res);
		if (CollectionUtils.isNotEmpty(dataList)) {
			for (Data data : dataList) {
				if (data.getState().equals("0")) {
					continue;
				}
				List<Traces> traces = data.getTraces();
				Traces trace = traces.get(traces.size() - 1);
				String callback = data.getCallBack();
				String[] converterOrderCode = converterOrderCode(callback);
				if (converterOrderCode == null) {
					continue;
				}
				String orderCode = converterOrderCode[0];
				Long userId = Long.parseLong(converterOrderCode[1]);
				sendNotice(data.getState(), orderCode, userId, data.getShipperCode(), data.getLogisticCode(), trace);
			}
		}

	}

	private void appendTracesDataBase(LogisticsTrackingResponse res) {
		appendTracesDataBase.execute(new Runnable() {
			public void run() {
				Date currentDate = new Date();

				List<LogisticsTraces> appendList = new ArrayList<>();
				List<Data> dataList = res.getData();
				if (CollectionUtils.isNotEmpty(dataList)) {
					for (Data data : dataList) {
						if (data.getState().equals("0")) {
							continue;
						}
						List<Traces> traces = data.getTraces();
						String callback = data.getCallBack();
						String[] converterOrderCode = converterOrderCode(callback);
						if (converterOrderCode == null) {
							continue;
						}
						String orderCode = converterOrderCode[0];
						List<LogisticsTraces> list = logisticsTracesService.findByOrderCode(orderCode, data.getLogisticCode());

						for (int i = list.size(); i < traces.size(); i++) {
							Traces t = traces.get(i);
							Boolean alreadyExist = traceAlreadyExist(t, list);
							if (!alreadyExist) {
								LogisticsTraces trace = new LogisticsTraces();
								trace.setEbusinessId(res.geteBusinessId());
								trace.setOrderCode(orderCode);
								trace.setShipperCode(data.getShipperCode());
								trace.setLogisticCode(data.getLogisticCode());
								trace.setState(data.getState());
								trace.setCallBack(data.getCallBack());
								trace.setAcceptTime(t.getAcceptTime());
								trace.setAcceptStation(t.getAcceptStation());
								trace.setRemark(t.getRemark());
								trace.setCreateTime(currentDate);
								appendList.add(trace);
							}

						}
						;
					}
				}
				if (CollectionUtils.isNotEmpty(appendList)) {
					logisticsTracesService.addBatch(appendList);
				}

			}
		});

	}

	private Boolean traceAlreadyExist(Traces t, List<LogisticsTraces> list) {
		if (CollectionUtils.isEmpty(list)) {
			return false;
		}
		for (LogisticsTraces exist : list) {
			if (t.getAcceptStation().trim().equals(exist.getAcceptStation().trim())) {
				return true;
			}
		}
		return false;

	}

	private void sendNotice(String state, String orderCode, Long userId, String shipperCode, String expressCode, Traces trace) {

		if (trace != null) {
			Logistics logistics = Logistics.valueOf(shipperCode);

			String link = null;
			boolean isNum = orderCode.matches("[0-9]+");
			if (isNum) {
				link = "/user/orderdetail.html?orderId=" + orderCode;
			} else {
				link = "/return/viewProgress.html";
			}
			String remark = "收到宝贝后请给予评价哦！评价会赠送优惠券一张哦,宝贝持续上新中，希望您继续关注壹果！";
			if (state.equals("2") && trace.getAcceptStation().indexOf("派件") > 0) {
				System.out.println("开始派件了");
				YgUser ygUser = ygUserService.findById(userId);
				String title = "宝贝派送中！很高兴遇见你，感谢你选择壹果！";
				wxMpMessageService.sendOrderDispatchNotice(ygUser, title, logistics.getTitle(), expressCode, link, remark);
			}
			if (state.equals("3")) {
				System.out.println("已签收");
				String recipienter = getRecipienter(trace.getAcceptStation());
				if (StringUtil.isNotBlank(recipienter)) {

					YgUser ygUser = ygUserService.findById(userId);
					String title = "亲，您的快递已签收。很高兴遇见你，感谢你选择壹果！";

					Date recipientTime = trace.getAcceptTime();
					wxMpMessageService.sendOrderReceiptNotice(ygUser, title, orderCode, recipienter, recipientTime, link, remark);
				}

			}
		}

	}

	private String[] converterOrderCode(String orderCode) {
		if (StringUtil.isNotBlank(orderCode) && orderCode.indexOf("_") > 0) {
			return orderCode.split("_");
		}
		return null;
	}

	private String getRecipienter(String acceptStation) {
		acceptStation = acceptStation.trim();
		if (acceptStation.indexOf("签收人") > 0) {
			acceptStation = acceptStation.substring(acceptStation.indexOf("签收人") + 4);
			return acceptStation.substring(0, acceptStation.indexOf(","));
		} else if (acceptStation.indexOf("已投递") > 0) {
			acceptStation = acceptStation.substring(acceptStation.indexOf("已投递") + 4);
			return acceptStation.substring(0, acceptStation.indexOf("】"));
		}
		return "";
	}

	/*
	 * public static void main(String[] args) { String res =
	 * "{\"PushTime\":\"2018-04-28 12:24:22\",\"EBusinessID\":\"1261725\",\"Data\":[{\"CallBack\":\"618042519573_30\",\"LogisticCode\":\"632091331860\",\"ShipperCode\":\"ZTO\",\"Traces\":[{\"AcceptStation\":\"【北京市】  【北京平谷】（010-69931119） 的 壹果 （13552989818） 已揽收\",\"AcceptTime\":\"2018-04-26 19:27:09\"},{\"AcceptStation\":\"【北京市】  快件离开 【北京平谷】 发往 【北京】\",\"AcceptTime\":\"2018-04-26 19:27:20\"},{\"AcceptStation\":\"[北京市]快件已到达北京\",\"AcceptTime\":\"2018-04-26 23:37:40\"},{\"AcceptStation\":\"[北京市]快件离开北京已发往上海\",\"AcceptTime\":\"2018-04-26 23:37:57\"},{\"AcceptStation\":\"[上海市]快件离开上海已发往普陀\",\"AcceptTime\":\"2018-04-27 20:56:15\"},{\"AcceptStation\":\"[上海市]普陀的业务员谢光为[13564072877]正在派件\",\"AcceptTime\":\"2018-04-28 09:15:53\"},{\"AcceptStation\":\"[上海市]快件已在普陀签收 签收人：拍照签收,感谢您使用中通快递，期待再次为您服务!\",\"AcceptTime\":\"2018-04-28 12:22:14\"}],\"State\":\"3\",\"OrderCode\":\"618042519573_30\",\"EBusinessID\":\"1261725\",\"Success\":true}],\"Count\":\"1\"}"
	 * ; KdNiaoCallBack kdNiaoCallBack = new KdNiaoCallBack();
	 * kdNiaoCallBack.doKdNiaoTraceCallBack(res); }
	 */
	public static void main(String[] args) {
		String callBack = "[郑州市]快件已投递【丰巢的河南省残疾人综合服务中心(丰巢智能快递柜)】如有问题请电联【4000633333】，感谢您使用中通快递，期待再次为您服务！";
		System.out.println(callBack.trim().indexOf("已投递"));
		callBack = callBack.substring(callBack.trim().indexOf("已投递") + 4);
		System.out.println(callBack);
		System.out.println(callBack.substring(0, callBack.indexOf("】")));
	}
}
